package cn.zbh.org.service.impl;

import cn.zbh.basic.service.impl.BasicServiceImpl;
import cn.zbh.basic.util.PageList;
import cn.zbh.org.domain.Department;
import cn.zbh.org.mapper.DepartmentMapper;
import cn.zbh.org.query.DepartmentQuery;
import cn.zbh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BasicServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    @Transactional
    public void add(Department department) {
        //返回自增长主键
        departmentMapper.add(department);
        //如果没有选择上级部门
        if(department.getParent_id()==null){
            //获取id
            Long id = department.getId();
            department.setDirPath("/"+id);

        }else {
            //选择了上级部门  parent_id：父级id
            Long parent_id = department.getParent_id();
            //通过parent_id获取父级对象
            Department parentDenartment = departmentMapper.findById(parent_id);
        department.setDirPath(parentDenartment.getDirPath()+"/"+department.getId());
        }
        //回调update方法 更新数据库
            update(department);


    }

    @Override
    @Transactional
    public void update(Department department) {
        if(department.getParent_id()==null){
            //获取id
            Long id = department.getId();
            department.setDirPath("/"+id);

        }else {
            //选择了上级部门  parent_id：父级id
            Long parent_id = department.getParent_id();
            //通过parent_id获取父级对象
            Department parentDenartment = departmentMapper.findById(parent_id);
            department.setDirPath(parentDenartment.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }








    @Override
    //  部门树
    public List<Department> deptTree() {

        List<Department> all= departmentMapper.findAll();//查询所有部门
        HashMap<Long, Department> map = new HashMap<>();
        for (Department department : all) {
            map.put(department.getId(),department);//将所有数据放入map中
        }
//前端需要得到的集合数据 - 部门树
       List<Department> deptTree = new ArrayList<>();
        for (Department department : all) {
            if(department.getParent_id()==null){//顶级部门
                deptTree.add(department);
            }else {
                //非顶级部门
                Long parent_id = department.getParent_id();//获取部门id
                Department parentDepartment = map.get(parent_id);//通过id获取 父 部门
                parentDepartment.getChildren().add(department);//

            }
        }

        return deptTree;
    }

}
